package com.tjetc.utils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tjetc.config.ApplicationContextProvider;
import com.tjetc.domain.ChatHistory;
import com.tjetc.repository.UserDao;
import com.tjetc.service.ChatHistoryService;
import com.tjetc.vo.Message;
import com.tjetc.vo.Result;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ConcurrentReferenceHashMap;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;




@ServerEndpoint(value = "/websocket/{id}",encoders = {ChatHistoryEncoder.class})
@Component
public class ChatEndpoint {
    private static RedisTemplate<String,Object> clusterRedisTemplate;
    // 存储所有客户端连接
    private static CopyOnWriteArraySet<ChatEndpoint> webSocketSet = new CopyOnWriteArraySet<>();
    //用来存储每一个客户端的Endpoint实例
    private static final Map<String, ChatEndpoint> onlineUsers = new ConcurrentReferenceHashMap<>();
    //声明session对象,通过该对象给指定用户发消息
    private Session session;
    //用户名
    private  String clientName;
    private static ChatHistoryService chatHistoryService;
    private static UserDao userDao;
	@Autowired
	public void setChatHistoryService(UserDao userDao) {
		ChatEndpoint.userDao = userDao;
	}
    @Autowired
    public void setChatHistoryService(ChatHistoryService chatHistoryService){
        ChatEndpoint.chatHistoryService=chatHistoryService;
    }

private UserDao userDao(){
    if(userDao==null){
        System.out.println("正在获取bean");
        ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
    if (applicationContext!=null){
        System.out.println("applicationContext = " + applicationContext);
        try {
            //尝试获取userDao
            userDao=applicationContext.getBean(UserDao.class);
            //测试
            System.out.println(userDao.findUsernameById(1));;
        }catch (Exception e){
            e.printStackTrace();
        }
        return userDao;
    }
    }
    System.out.println("userDao不是null");
    return userDao;
}
    private RedisTemplate<String, Object> redisTemplate() {
        if (clusterRedisTemplate == null) {
            System.out.println("正在获取RedisTemplate bean");
            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            if (applicationContext != null) {
                System.out.println("applicationContext = " + applicationContext);
                try {
                    //尝试获取默认的redisTemplate
                    clusterRedisTemplate = applicationContext.getBean("redisTemplate", RedisTemplate.class);
                    System.out.println("成功获取RedisTemplate: " + clusterRedisTemplate);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return clusterRedisTemplate;
            }
        }
        System.out.println("clusterRedisTemplate不是null");
        return clusterRedisTemplate;
    }
    private ChatHistoryService chatHistoryService(){
        if(chatHistoryService==null){
            System.out.println("正在获取bean");
            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            if (applicationContext!=null){
                System.out.println("applicationContext = " + applicationContext);
                try {
                    //尝试获取userDao
                    chatHistoryService=applicationContext.getBean(ChatHistoryService.class);
                    //测试

                }catch (Exception e){
                    e.printStackTrace();
                }
                return chatHistoryService;
            }
        }
        System.out.println("chatHistoryService不是null");
        return chatHistoryService;
    }

    @OnOpen
//连接建立时执行
    public void onOPen(Session session, @PathParam("id") String id, EndpointConfig config) throws IOException {
        UserDao userDao=userDao();
        webSocketSet.add(this);
        this.session = session;
        String username = userDao.findUsernameById(Integer.valueOf(id)).getUsername();
        this.clientName=username;
        //将当前对象存储到容器中
        onlineUsers.put(username, this);
        System.out.println("用户" + username + "上线了");
        //将当前用户推送给所有客户端
        //1.获取消息
        String message = ("您的好友" + username + "上线了");
        //2.调用系统消息的推送
        broadcastAllUsers(id);
        System.out.println("session.isOpen=" + session.isOpen());
    }
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("WebSocket发生错误: " + error.getMessage());
        error.printStackTrace();
    }
    private void broadcastAllUsers(String message) {
        try {
            Set<String> keySet = onlineUsers.keySet();
            for (String s : keySet) {
                Message message1 = new Message();
                message1.setContent(message);
                message1.setSenderType("system");
                long currentTime = System.currentTimeMillis();
                message1.setTimestamp(currentTime); // 添加时间戳
                message1.setTime(currentTime); // 添加time字段以兼容前端
                Gson gson = new Gson();
                String json = gson.toJson(message1);
                ChatEndpoint chatEndpoint = onlineUsers.get(s);
                synchronized (chatEndpoint.session){
                    chatEndpoint.session.getBasicRemote().sendText(json);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private Set<String> getNames() {
        return onlineUsers.keySet();
    }


    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("=== 后端收到消息 ===");
        ChatHistory chatHistory = new ChatHistory();
        ChatHistory chatHistory1=new ChatHistory();
        System.out.println("message = " + message);
        JsonElement jsonElement=JsonParser.parseString(message);
        if (jsonElement.isJsonObject()){
            JsonObject jsonObject = JsonParser.parseString(message).getAsJsonObject();
            int receiverId=jsonObject.get("receiverId").getAsInt();
            String content=jsonObject.get("content").getAsString();
            int senderId=jsonObject.get("senderId").getAsInt();
            String type=jsonObject.get("type").getAsString();
//            boolean isArtificial=jsonObject.get("isArtificial").getAsBoolean();
            System.out.println("receiverId = " + receiverId);
            System.out.println("content = " + content);
            System.out.println("senderId = " + senderId);
            System.out.println("type = " + type);
//            System.out.println("isArtificial = " + isArtificial);
            if (jsonObject.get("receiverId").getAsInt()==8){


                try {
                    chatHistory.setIsRead(false).setReceiverId(8).setSenderId(senderId).setContent(content).setDate(new Date()).setSenderType("user").setStatus(1).setType(type);
//                    System.out.println("chatHistory = " + chatHistory);
                    chatHistoryService.add(chatHistory);
                    onlineUsers.get(userDao().findUsernameById(senderId).getUsername()).session.getBasicRemote().sendObject(chatHistory);
                    String chat;
                    if (redisTemplate().opsForValue().get(content)!=null){
                        chat=redisTemplate().opsForValue().get(content).toString();
                    }else {
                        chat = AiUtils.chat(content);
                        redisTemplate().opsForValue().set(content,chat,1, TimeUnit.DAYS);
                    }
                  chatHistory1.setIsRead(false).setReceiverId(senderId).setSenderId(8).setContent(chat).setDate(new Date()).setSenderType("user").setStatus(1).setType(type);
//                    System.out.println("chatHistory1 = " + chatHistory1);
                    chatHistoryService.add(chatHistory1);
                    onlineUsers.get(userDao().findUsernameById(senderId).getUsername()).session.getBasicRemote().sendObject(chatHistory1);

                } catch (Exception e) {

                    e.printStackTrace();
                }
            }else {


                if (onlineUsers.get(userDao.findUsernameById(receiverId).getUsername()) != null) {
                    if (jsonObject.get("status") == null) {
                        chatHistory.setIsRead(false).setReceiverId(receiverId).setSenderId(senderId).setContent(content).setDate(new Date()).setSenderType("user").setStatus(1).setType(type);
                        System.out.println("系统第一次收到消息");
                        System.out.println("chatHistory = " + chatHistory);
                        try {
                            System.out.println("开始第一次发给接收方");
                            onlineUsers.get(userDao().findUsernameById(receiverId).getUsername()).session.getBasicRemote().sendObject(chatHistory);
                        } catch (EncodeException e) {
                            e.printStackTrace();
                        }
                    } else if (jsonObject.get("status").getAsInt() == 1) {
                        chatHistory.setIsRead(false).setReceiverId(receiverId).setSenderId(senderId).setContent(content).setDate(new Date()).setSenderType("user").setStatus(2).setType(type);
                        System.out.println("系统第2次收到消息");
                        System.out.println("chatHistory = " + chatHistory);
                        try {
                            System.out.println("开始第一次发给发送方");
                            onlineUsers.get(userDao().findUsernameById(senderId).getUsername()).session.getBasicRemote().sendObject(chatHistory);
                        } catch (EncodeException e) {
                            e.printStackTrace();
                        }
                    } else if (jsonObject.get("status").getAsInt() == 2) {
                        chatHistory.setIsRead(false).setReceiverId(receiverId).setSenderId(senderId).setContent(content).setDate(new Date()).setSenderType("user").setStatus(3).setType(type);
                        System.out.println("系统第3次收到消息");
                        System.out.println("chatHistory = " + chatHistory);
                        try {
                            System.out.println("开始第二次发给接收方");
                            onlineUsers.get(userDao().findUsernameById(receiverId).getUsername()).session.getBasicRemote().sendObject(chatHistory);
                            Result result = chatHistoryService.add(chatHistory);
                            if (result.getCode() == 200) {
                                System.out.println("插入成功");
                            } else {
                                System.out.println("插入失败");
                            }
                        } catch (EncodeException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    System.out.println("接收方不在线");
                    chatHistory.setIsRead(false).setReceiverId(receiverId).setSenderId(senderId).setContent(content).setDate(new Date()).setSenderType("user").setStatus(4).setType(type);
                    try {
                        System.out.println(chatHistory.getDate());
                        onlineUsers.get(userDao().findUsernameById(senderId).getUsername()).session.getBasicRemote().sendObject(chatHistory);
                        chatHistoryService.add(chatHistory);
                    } catch (EncodeException e) {
                        e.printStackTrace();
                    }
                }
            }

        }else {
            System.out.println("不是JSON格式!!!!!");
        }






        System.out.println("结束");
        System.out.println("chatHistory = " + chatHistory);


    }


    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        onlineUsers.remove(clientName);
        System.out.println(clientName+"下线了");
    }

}
